/**
 * 展示群成员列表
 */
import c from 'classnames'
import { FixedSizeList as List } from 'react-window'
import Member from './Member'
import { type AtMember, type AtMembers, useHighlight } from './logics'
import './Members.module.less'

// 渲染用到的 CSS 值，取自 Members.module.less、Member.module.less
const listMaxHeight = 160
const listWidth = 160
const itemSize = 32

export default function Members(props: {
  members: AtMembers
  position: { left: number; bottom: number }
  creatorWxid: string
  onConfirm: (member: AtMember) => void
}) {
  const { position, creatorWxid, members, onConfirm } = props
  const listRef = useRef<HTMLDivElement>(null)
  const { highlight, mouseSetHighlight } = useHighlight(members, listRef, onConfirm)

  const formattedData = useMemo(() => {
    return members.map(member => ({
      member,
      isCreator: member.userId === creatorWxid,
      isHighlight: highlight === member.userId,
    }))
  }, [members, highlight, creatorWxid])
  const itemKey = useCallback(
    (index: number, list: typeof formattedData) => list[index]!.member.userId,
    [],
  )
  const RenderItem = useCallback(
    ({
      data,
      index,
      style,
    }: {
      data: typeof formattedData
      index: number
      style: React.CSSProperties
    }) => {
      const { member, isCreator, isHighlight } = data[index]!
      return <Member
        member={member}
        isCreator={isCreator}
        isHighlight={isHighlight}
        highlight={mouseSetHighlight}
        confirm={onConfirm}
        style={style}
      />
    },
    [onConfirm, mouseSetHighlight],
  )

  return <div
    styleName={c('list-wrap')}
    style={{ left: `${position.left}px`, bottom: `${position.bottom}px` }}
  >
    <List
      height={Math.min(listMaxHeight, members.length * itemSize)}
      width={listWidth}
      itemSize={itemSize}
      itemCount={members.length}
      itemData={formattedData}
      itemKey={itemKey}
      outerRef={listRef}
    >
      {RenderItem}
    </List>

    <div styleName="arrow"></div>
  </div>
}
